package com.notes.romania.browser;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.notes.romania.R;
import com.notes.romania.arrayadapter.FileArrayAdapter;

public class FileBrowser extends Activity {
	private ArrayList<String> values;
	private FileArrayAdapter adapter;
	
	private ListView listView;
	
	private File mainDir;
	private File currentDir;
	private File [] files;
	
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.file_browser);
		
		values = new ArrayList <String>();
		
		adapter = new FileArrayAdapter(this, new ArrayList<String>());
		listView = (ListView)findViewById(R.id.listView1);
		listView.setAdapter(adapter);
		
		mainDir = Environment.getExternalStorageDirectory();
		currentDir = Environment.getExternalStorageDirectory();
		
		updateList();
		
		listView.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(position == 0){
					if(currentDir.getAbsolutePath().equals(mainDir.getAbsolutePath()))	//Remain here
						return;
					
					currentDir = currentDir.getParentFile();
					//Toast.makeText(FileBrowser.this, "back", Toast.LENGTH_LONG).show();
					updateList();
					return;
				}
				if(files[position - 1].isDirectory()){	//Advance 
					currentDir = files[position - 1];
					
					//Toast.makeText(FileBrowser.this, "advance", Toast.LENGTH_LONG).show();
					updateList();
					return;
				}
				//Is music file. We will send sound path back to main activity
				Intent resultIntent = new Intent();
				resultIntent.putExtra("soundPath", files[position - 1].getAbsolutePath());
				setResult(Activity.RESULT_OK, resultIntent);
				finish();
			}});
	}
	
	void readFiles(){
		values.clear();
		values.add("back");
		
		FileFilter ff = new FileFilter() {
			public boolean accept(File pathname) {
				if(pathname.isDirectory())
					return true;
				if(pathname.getName().endsWith(".mp3"))
					return true;
				return false;
			}
		};
		files = currentDir.listFiles(ff);
		for(int i = 0; i < files.length; i ++)
			values.add(files[i].getName());
	}
	
	void updateList(){
		readFiles();
		adapter.clear();
		adapter.addAll(values);
	}
	
} 